<template>
  <div class="sendCode">
    <el-button @click="send"
               :disabled="isdisabled">{{btnVal}}</el-button>
  </div>
</template>

<script>
import { validatPhone } from '@/utils/validate'

export default {
  name: 'sendCode',
  props: ['phone'],
  data () {
    return {
      time: 60,
      isdisabled: false, //能用
      btnVal: '发送验证码',
    }
  },
  methods: {
    send () {
      if (validatPhone(this.phone)) {
        this.CountDown()
        this.getCode()
      } else {
        this.$message.error('手机号错误,请重新输入')
      }
    },
    async getCode () {  //获取验证码
      try {
        const res = await this.api.verify({ phone: this.phone })
        if (res.code == 1) {
          this.$message({ message: res.msg, type: 'success' })
        } else {
          this.$message.error(res.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    CountDown () {  //倒计时
      this.isdisabled = true;
      var interval = window.setInterval(() => {
        this.btnVal = '(' + this.time + ')秒后';
        --this.time;
        if (this.time < 0) {
          this.btnVal = '重新发送';
          this.isdisabled = false;
          this.time = 60;
          window.clearInterval(interval);
        }
      }, 1000)
    }
  }

}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.sendCode {
  height: 100%;
  button {
    height: 100%;
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: none;
    color: #fff;
  }
  button:hover {
    background: none;
  }
}
</style>
